import { createWebHistory, createRouter, RouteRecordRaw } from "vue-router";
import { storeToRefs } from 'pinia'
// 获取动态路由信息
import {useMenu} from '../store/menu';

let component = () => import("../views/home/index.vue");

export const routes: Array<RouteRecordRaw> = [
  {
    path: "/login",
    name: "login",
    component: () => import("../views/login/index.vue"),
  },
  {
    path: "/home",
    name: "home",
    component: () => import("../views/home/index.vue"),
  },
  {
    path: "/404",
    name: "404",
    component: () => import("../views/404.vue"),
  },
];

let base = import.meta.env.VITE_APP_PUBLIC_PATH;
const router = createRouter({
  history: createWebHistory(
    import.meta.env.MODE === "production" ? "/" + base + "/" : "/"
  ),
  routes: routes,
});

let state = false;

router.beforeEach( async(to, from, next) =>{
  console.log('----------to------', to)
  // let token = localStorage.getItem('token');
  // if(!token) {
  //   return next({name: 'login'})
  // }
  if(to.path === '/login' || to.path === '/home') {
    return next();
  }

   // 验证当前路由是否存在
   let currList = localStorage.getItem('effectiveUrl') || '[]';
   let effectiveUrl:[] = JSON.parse(currList);
   console.log('----------currList------', effectiveUrl)
   if(effectiveUrl.length) {
      if(!effectiveUrl.includes(to.path)) {
        return next({ path: '/home' });
      }
   } else {
    console.log('----------22222222222------')
     next({name: 'login'})
   }

   // 验证是否已经绑定过路由
   if(!state) {
     await bindRouter();
     state = true;
    return next({path: to.fullPath});
     
   }
  next();
})

/**
 * 绑定动态路由
 */
function bindRouter() {
  return new Promise((resolve:any) => {
    const useMenuStore = useMenu();
    const { routerList } = storeToRefs(useMenuStore);

    let routerListLocal:any = [];
    let arrayRoutes:any = localStorage.getItem('routerList');
    routerListLocal =  JSON.parse(arrayRoutes);
    let newRoutes =  Object.keys(routerList.value).length ? routerList.value : routerListLocal;  //
    newRoutes.forEach((item:any) => {
      if(!isRouteDuplicated(item)) {
        router.addRoute({
          path: item.path,
          name: item.name,
          component: component
        })
      }  
    })
    resolve();
  })
}

/**
 * 判断当前路由是否已经存在
 * @param to 
 * @returns 
 */
function isRouteDuplicated(to:any) {
  return router.currentRoute.value.path === to.path || router.currentRoute.value.matched.some(record => record.path === to.path);
}

export default router;
